package com.secneo.appshare.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsAdapter;
import com.secneo.appshare.adapter.FeedsButtonAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.Feeds;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.AppSharePreference;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.FeedsThread;
import com.secneo.appshare.threads.PhoneListThread;
import com.secneo.mp.api.database.DatabaseHelper;

public class MainSquareActivity extends CommonActivity implements OnScrollListener
{
	public static boolean mRecyleFlag = false;
	private ProgressDialog mProgressDialog = null;

	private int feed_get_type;
	// 获取feed的类型：全部用户（feedGetTypeAll）或者同机型用户（feedGetTypeByPhone）
	private int feedLastItem = 0;
	private int pageNumber = 1;

	private boolean phoneFeedsShow = false;
	private boolean allowFeedAgain = true;

	private LinearLayout mPhoneTypeHeadLayout;
	private TextView mPhoneNameTextView;
	private Button mBtnAttentAll;
	private String mSelectedPhoneName;
	private GridView mFeedsGridView;
	private ListView mPhoneListView;

	private PhoneListThread mPhoneListThread = null;
	private FeedsThread mFeedsThread = null;

	private RadioGroup mRadioGroup;
	private RadioButton btnFieldAll;
	private RadioButton btnFieldSamePhone;

	private List<String> phoneList;
	List<Feed> feedList = new ArrayList<Feed>();
	int feedSelectionFlag = 0;
	int feednum = 0;
	FeedsAdapter feedAdapter = null;
	FeedsButtonAdapter feedButtonAdapter = null;
	private PhoneAdapter mPhoneAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_square);
		setContext(this);

		feed_get_type = Constants.feedGetTypeAll;

		mPhoneTypeHeadLayout = (LinearLayout) findViewById(R.id.expand_phone_type_head);
		mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		mPhoneNameTextView = (TextView) findViewById(R.id.phone_type_text);

		mBtnAttentAll = (Button) findViewById(R.id.btn_attent_all);
		mBtnAttentAll.setVisibility(View.GONE);
		mBtnAttentAll.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh = new DatabaseHelper(MainSquareActivity.this);
				dh.insertUserAppPopularityBycatagory(MainSquareActivity.this, 2044);
				dh.close();

				startAttentThread();
			}
		});

		FeedsGridViewItemClickListener listener = new FeedsGridViewItemClickListener();
		mFeedsGridView = (GridView) findViewById(R.id.square_grid);
		mFeedsGridView.setOnItemClickListener(listener);
		mFeedsGridView.setOnScrollListener(this);
		feedList = new ArrayList<Feed>();

		mPhoneListView = (ListView) findViewById(R.id.listview_same_phone);
		mPhoneListView.setDivider(getResources().getDrawable(R.drawable.list_divider));
		mPhoneListView.setAdapter(mPhoneAdapter);
		mPhoneListView.setOnItemClickListener(new PhoneListViewItemClickListener());
		mPhoneAdapter = new PhoneAdapter(MainSquareActivity.this, phoneList);
		phoneList = new ArrayList<String>();

		btnFieldAll = (RadioButton) findViewById(R.id.btnFieldAll);
		btnFieldAll.setChecked(true);
		btnFieldAll.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				DatabaseHelper dh = new DatabaseHelper(MainSquareActivity.this);
				dh.insertUserAppPopularityBycatagory(MainSquareActivity.this, 2042);
				dh.close();

				endChildrenThreads();

				feed_get_type = Constants.feedGetTypeAll;
				mPhoneTypeHeadLayout.setVisibility(View.GONE);
				mBtnAttentAll.setVisibility(View.GONE);
				Message msg = new Message();
				msg.what = Constants.MSG_START_FEEDS_THREAD;
				mFeedsHandler.sendMessage(msg);
			}
		});
		btnFieldSamePhone = (RadioButton) findViewById(R.id.btnFieldSamePhone);
		btnFieldSamePhone.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				DatabaseHelper dh = new DatabaseHelper(MainSquareActivity.this);
				dh.insertUserAppPopularityBycatagory(MainSquareActivity.this, 2043);
				dh.close();

				endChildrenThreads();

				String title = MainSquareActivity.this.getResources().getString(R.string.title_top10_phone);
				mPhoneNameTextView.setText(title);

				initViewPreWorkingThread();
				mPhoneTypeHeadLayout.setVisibility(View.VISIBLE);
				mBtnAttentAll.setVisibility(View.GONE);
				startPhoneListThread();
			}
		});

		initViewPreWorkingThread();
		startFeedsThread();
	}

	@Override
	protected void onPause()
	{
		if (mRecyleFlag)
		{
			// 回收资源
			mRecyleFlag = false;
			endChildrenThreads();
		}
		super.onPause();
	}

	@Override
	protected void onNewIntent(Intent intent)
	{
		Boolean needInit = intent.getBooleanExtra("FromGroup", false);
		if (needInit)
		{
			// 重新获取资源
			initViewPreWorkingThread();
			endChildrenThreads();

			btnFieldAll.setChecked(true);

			feed_get_type = Constants.feedGetTypeAll;
			mPhoneTypeHeadLayout.setVisibility(View.GONE);
			mBtnAttentAll.setVisibility(View.GONE);
			startFeedsThread();
		}
		super.onNewIntent(intent);
	}

	/* 退出处理 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (phoneFeedsShow)
			{
				phoneFeedsShow = false;

				String title = MainSquareActivity.this.getResources().getString(R.string.title_top10_phone);
				mPhoneNameTextView.setText(title);

				initViewPreWorkingThread();
				mBtnAttentAll.setVisibility(View.GONE);
				startPhoneListThread();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void endChildrenThreads()
	{
		if (mPhoneListThread != null)
		{
			mPhoneListThread.stopRun();
			mPhoneListThread = null;
		}
		if (mFeedsThread != null)
		{
			mFeedsThread.stopRun();
			mFeedsThread = null;
		}

		mFeedsGridView.setAdapter(null);
		if (feedAdapter != null)
		{
			feedAdapter.freeDrawable();
		}
		if (feedButtonAdapter != null)
		{
			feedButtonAdapter.freeDrawable();
		}

		mPhoneListView.setAdapter(null);
		if (mPhoneAdapter != null)
		{
			mPhoneAdapter.freeDrawable();
		}

	}

	private void initViewPreWorkingThread()
	{
		View errorView = MainSquareActivity.this.findViewById(R.id.view_network_error);
		errorView.setVisibility(View.GONE);
		mFeedsGridView.setVisibility(View.GONE);
		mPhoneListView.setVisibility(View.GONE);

		startProgressDialog();
	}

	private Handler mFeedsHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				// 获得用户网络错误
				case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
					stopProgressDialog();

					View errorView = MainSquareActivity.this.findViewById(R.id.view_network_error);
					errorView.setVisibility(View.VISIBLE);

					break;

				case Constants.MSG_GET_FEEDS_FINISH:

					stopProgressDialog();
					allowFeedAgain = true;

					if (feed_get_type == Constants.feedGetTypeAll)
					{
						phoneFeedsShow = false;
						refreshFeedsGridView(mFeedsThread.getFeeds());
					} else if (feed_get_type == Constants.feedGetTypeByPhone)
					{
						phoneFeedsShow = true;
						refreshFeedsButtonGridView(mFeedsThread.getFeeds());
					}
					break;

				case Constants.MSG_GET_FEEDICON_FINISH:
					mFeedsGridView.invalidateViews();
					break;

				case Constants.MSG_START_FEEDS_THREAD:
					initViewPreWorkingThread();
					startFeedsThread();
					break;
			}
			super.handleMessage(msg);
		}
	};

	private Handler mPhoneListHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_TOP_PHONE_LIST_FINISH:
					try
					{
						refreshTopPhoneListView(mPhoneListThread.getPhoneList());

					} catch (Exception ex)
					{
						ex.printStackTrace();
					}
					break;

				case Constants.MSG_GET_TOP_PHONE_NETWORK_ERROR:
					try
					{
						stopProgressDialog();

						View errorView = MainSquareActivity.this.findViewById(R.id.view_network_error);
						errorView.setVisibility(View.VISIBLE);

					} catch (Exception ex)
					{
						ex.printStackTrace();
					}
					break;

			}

			super.handleMessage(msg);
		}
	};

	private Handler mAttentMultipleHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			stopProgressDialog();
			switch (msg.what)
			{
				case Constants.MSG_ATTENT_MULTIPLE_FINISH:
					try
					{
						feedButtonAdapter.setFeedList(feedList);
						feedButtonAdapter.notifyDataSetChanged();

					} catch (Exception ex)
					{
						ex.printStackTrace();
					}
					break;

				case Constants.MSG_ATTENT_SINGLE_FINISH:
					try
					{
						String finishedUid = feedButtonAdapter.getFinishedUid();

						int size = feedList.size();
						for (int i = 0; i < size; i++)
						{
							Feed feed = feedList.get(i);
							if (feed.uid.equals(finishedUid))
							{
								feedList.get(i).is_attent = 1;
								break;
							}
						}

						feedButtonAdapter.setFeedList(feedList);
						feedButtonAdapter.notifyDataSetChanged();

					} catch (Exception ex)
					{
						ex.printStackTrace();
					}
					break;
			}

			super.handleMessage(msg);
		}
	};

	private void startFeedsThread()
	{
		String uid = LocalStore.getLocaleStoreInstance(this).getUid();
		pageNumber = 1;
		for (int i = 0; i < feedList.size(); i++)
		{
			feedList.get(i).user_icon_drawable = null;
		}
		feedList.clear();
		System.gc();

		feedSelectionFlag = 0;
		feednum = 0;
		feedAdapter = null;
		mFeedsThread = new FeedsThread(this, mFeedsHandler, pageNumber, uid, Constants.USER_TYPE_FIELD, feed_get_type);
		mFeedsThread.setPhoneType(mSelectedPhoneName);
		mFeedsThread.start();
	}

	private void startPhoneListThread()
	{
		mPhoneAdapter = null;
		mPhoneListThread = new PhoneListThread(this, mPhoneListHandler, Constants.phoneListCount);
		mPhoneListThread.start();
	}

	private void startAttentThread()
	{
		Thread followMultipleThread = new Thread()
		{
			public void run()
			{
				final String uid = LocalStore.getLocaleStoreInstance(MainSquareActivity.this).getUid();
				final List<String> uidList = new ArrayList<String>();

				int size = mFeedsThread.getFeeds().feeds.size();
				for (int i = 0; i < size; i++)
				{
					Feed feed = mFeedsThread.getFeeds().feeds.get(i);
					if (1 != feed.is_attent)
					{
						uidList.add(feed.uid);
					}
				}

				RemoteApiImpl remoteApi = new RemoteApiImpl();
				boolean ret = remoteApi.uploadFollowedFriends(MainSquareActivity.this, uid, uidList);
				if (ret)
				{
					size = mFeedsThread.getFeeds().feeds.size();
					int uidListSize = 0;
					for (int i = 0; i < size; i++)
					{
						uidListSize = uidList.size();
						Feed feed = mFeedsThread.getFeeds().feeds.get(i);
						for (int j = 0; j < uidListSize; j++)
						{
							if (feed.uid.equals(uidList.get(j)))
							{
								mFeedsThread.getFeeds().feeds.get(i).is_attent = 1;
								uidList.remove(j);
								break;
							}
						}
					}
					Message msg = new Message();
					msg.what = Constants.MSG_ATTENT_MULTIPLE_FINISH;
					mAttentMultipleHandler.sendMessage(msg);
				}
			}
		};
		followMultipleThread.start();
	}

	public void refreshFeedsGridView(Feeds feeds)
	{
		if (feeds == null || feeds.feeds.size() == 0)
			return;

		// FeedsAdapter ap = new FeedsAdapter(this, feeds);
		mFeedsGridView.setVisibility(View.VISIBLE);
		mFeedsGridView.setVisibility(View.VISIBLE);
		mPhoneListView.setVisibility(View.GONE);
		try
		{
			for (int i = 0; i < feeds.feeds.size(); i++)
			{
				Feed la = feeds.feeds.get(i);
				feedList.add(la);
			}

		} catch (Exception ex)
		{
			Log.d("MyTag", "feedList add error = " + ex.getMessage());
			ex.printStackTrace();
		}

		if (feednum == 0)
		{
			feedAdapter = new FeedsAdapter(this, feedList);
			mFeedsGridView.setNumColumns(4);
			mFeedsGridView.setNumColumns(4);
			mFeedsGridView.setAdapter(feedAdapter);
			mFeedsGridView.setAdapter(feedAdapter);
		}

		if (Constants.feedPageFlag)
		{
			feedSelectionFlag = feedSelectionFlag + 40;
			feedAdapter.notifyDataSetChanged();
			if (feednum == 0)
			{
				mFeedsGridView.setSelection(0);
			} else
			{
				mFeedsGridView.setSelection(feedSelectionFlag);
			}
			feednum += 40;
		}
	}

	public void refreshFeedsButtonGridView(Feeds feeds)
	{
		if (feeds == null || feeds.feeds.size() == 0)
			return;

		// FeedsAdapter ap = new FeedsAdapter(this, feeds);
		mFeedsGridView.setVisibility(View.VISIBLE);
		mFeedsGridView.setVisibility(View.VISIBLE);
		mPhoneListView.setVisibility(View.GONE);

		try
		{
			for (int i = 0; i < feeds.feeds.size(); i++)
			{
				Feed la = feeds.feeds.get(i);
				feedList.add(la);
			}

		} catch (Exception ex)
		{
			Log.d("MyTag", "feedButtonList add error = " + ex.getMessage());
			ex.printStackTrace();
		}

		if (feednum == 0)
		{
			feedButtonAdapter = new FeedsButtonAdapter(this, mAttentMultipleHandler, feedList);
			mFeedsGridView.setNumColumns(4);
			mFeedsGridView.setAdapter(feedButtonAdapter);
		}

		if (Constants.feedPageFlag)
		{
			feedSelectionFlag = feedSelectionFlag + 40;
			feedButtonAdapter.notifyDataSetChanged();
			if (feednum == 0)
			{
				mFeedsGridView.setSelection(0);
			} else
			{
				mFeedsGridView.setSelection(feedSelectionFlag);
			}
			feednum += 40;
		}
	}

	public void refreshTopPhoneListView(List<String> list)
	{

		stopProgressDialog();

		if (list == null)
			return;

		mFeedsGridView.setVisibility(View.GONE);
		mPhoneListView.setVisibility(View.VISIBLE);

		phoneList = list;

		mPhoneAdapter = new PhoneAdapter(this, phoneList);
		mPhoneListView.setAdapter(mPhoneAdapter);
	}

	public class PhoneAdapter extends BaseAdapter
	{
		Context ctx;
		private List<String> phoneList;

		public PhoneAdapter(Context ctx, List<String> phoneList)
		{
			this.ctx = ctx;
			this.phoneList = phoneList;
		}

		@Override
		public int getCount()
		{
			return phoneList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		public void freeDrawable()
		{
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			TextView phoneNameView;
			final int selected_position = position;
			if (convertView == null)
			{
				View v = LayoutInflater.from(MainSquareActivity.this).inflate(R.layout.appshare_phone_list_item, null);
				phoneNameView = (TextView) v.findViewById(R.id.phoneName);
				v.setTag(phoneNameView);
				convertView = v;
			} else
			{
				phoneNameView = (TextView) convertView.getTag();
			}

			final String phoneName = phoneList.get(position);
			phoneNameView.setText(phoneName);

			phoneNameView.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
				}
			});

			return convertView;
		}
	}

	class PhoneListViewItemClickListener implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			mSelectedPhoneName = phoneList.get(position);
			mPhoneNameTextView.setText(mSelectedPhoneName);
			mPhoneTypeHeadLayout.setVisibility(View.VISIBLE);
			mBtnAttentAll.setVisibility(View.VISIBLE);

			feed_get_type = Constants.feedGetTypeByPhone;
			Message msg = new Message();
			msg.what = Constants.MSG_START_FEEDS_THREAD;
			mFeedsHandler.sendMessage(msg);
		}
	}

	class FeedsGridViewItemClickListener implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			if (!AppSharePreference.isAppShareUserLogined(MainSquareActivity.this))
			{
				Intent intent = new Intent();
				intent.setClass(MainSquareActivity.this, LoginChooseMethodActivity.class);
				startActivity(intent);
			} else
			{
				try
				{
					Intent intent = new Intent();
					intent.setClass(MainSquareActivity.this, AppsOtherUserActivity.class);

					Bundle mBundle = new Bundle();
					String uid = LocalStore.getLocaleStoreInstance(MainSquareActivity.this).getUid();
					mBundle.putString("uid", uid);

					Feed feed = feedList.get(position);
					mBundle.putString("other_uid", feed.uid);
					mBundle.putString("user_icon", feed.user_icon);
					mBundle.putString("user_name", feed.user_name);

					intent.putExtras(mBundle);
					startActivity(intent);

				} catch (Exception ex)
				{
					ex.printStackTrace();
				}
			}
		}
	}

	private void startProgressDialog()
	{
		View view = findViewById(R.id.view_network_error);
		view.setVisibility(View.GONE);
		if (mProgressDialog != null)
			mProgressDialog.dismiss();
		mProgressDialog = new ProgressDialog(MainSquareActivity.this);
		mProgressDialog.setMessage("加载中，请稍候...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}

	private void stopProgressDialog()
	{
		if (mProgressDialog != null)
		{
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{
		feedLastItem = firstVisibleItem + visibleItemCount;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState)
	{
		// TODO Auto-generated method stub

		try
		{
			if (Constants.feedGetTypeAll == feed_get_type)
			{
				if (feedAdapter != null && feedLastItem == feedAdapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
				{
					if (!allowFeedAgain)
						return;
					String uid = LocalStore.getLocaleStoreInstance(MainSquareActivity.this).getUid();
					pageNumber++;
					if (pageNumber > 5)
						return;
					allowFeedAgain = false;
					mProgressDialog = new ProgressDialog(MainSquareActivity.this);
					mProgressDialog.setMessage("加载中，请稍候...");
					mProgressDialog.show();
					mFeedsThread = new FeedsThread(this, mFeedsHandler, pageNumber, uid, Constants.USER_TYPE_FIELD, feed_get_type);
					mFeedsThread.start();
				}
			} else if (Constants.feedGetTypeByPhone == feed_get_type)
			{
				if (feedButtonAdapter != null && feedLastItem == feedButtonAdapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
				{
					if (!allowFeedAgain)
						return;
					String uid = LocalStore.getLocaleStoreInstance(MainSquareActivity.this).getUid();
					pageNumber++;
					if (pageNumber > 5)
						return;
					allowFeedAgain = false;
					mProgressDialog = new ProgressDialog(MainSquareActivity.this);
					mProgressDialog.setMessage("加载中，请稍候...");
					mProgressDialog.show();
					mFeedsThread = new FeedsThread(this, mFeedsHandler, pageNumber, uid, Constants.USER_TYPE_FIELD, feed_get_type);
					mFeedsThread.setPhoneType(mSelectedPhoneName);
					mFeedsThread.start();
				}
			}

		} catch (Exception ex)
		{
			Log.d("MyTag", "onScrollStateChanged error = " + ex.getMessage());
			ex.printStackTrace();
		}
	}
}